package example.NIOUDPTest;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;

public class SimpleUdpClient {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8888;
    private static final Charset charset = Charset.forName("UTF-8");
    
    public static void main(String[] args) {
        System.out.println("UDP 时间客户端启动");
        System.out.println("支持命令: time, date, timestamp, quit");
        
        try (DatagramChannel channel = DatagramChannel.open()) {
            channel.configureBlocking(false);
            
            // 连接服务器（UDP的connect只是设置默认目标，不是真正连接）
            channel.connect(new InetSocketAddress(SERVER_HOST, SERVER_PORT));
            
            Scanner scanner = new Scanner(System.in);
            Selector selector = Selector.open();
            channel.register(selector, SelectionKey.OP_READ);
            
            while (true) {
                System.out.print("请输入命令> ");
                String command = scanner.nextLine().trim();
                
                if ("quit".equalsIgnoreCase(command)) {
                    System.out.println("客户端退出");
                    break;
                }
                
                if (command.isEmpty()) {
                    continue;
                }
                
                // 发送请求
                sendRequest(channel, command);
                
                // 等待响应
                waitForResponse(channel, selector, command);
            }
            
            scanner.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void sendRequest(DatagramChannel channel, String command) {
        try {
            ByteBuffer buffer = charset.encode(command);
            channel.write(buffer);
            System.out.println("已发送请求: " + command);
        } catch (Exception e) {
            System.err.println("发送请求时出错: " + e.getMessage());
        }
    }
    
    private static void waitForResponse(DatagramChannel channel, Selector selector, String command) {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            long startTime = System.currentTimeMillis();
            boolean responseReceived = false;
            
            // 等待5秒内的响应
            while (System.currentTimeMillis() - startTime < 5000) {
                int readyChannels = selector.select(1000); // 等待1秒
                
                if (readyChannels > 0) {
                    Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                    while (keyIterator.hasNext()) {
                        SelectionKey key = keyIterator.next();
                        keyIterator.remove();
                        
                        if (key.isReadable()) {
                            buffer.clear();
                            channel.read(buffer);
                            buffer.flip();
                            
                            String response = charset.decode(buffer).toString();
                            System.out.println("服务器响应: " + response);
                            responseReceived = true;
                            break;
                        }
                    }
                }
                
                if (responseReceived) {
                    break;
                }
            }
            
            if (!responseReceived) {
                System.out.println("等待响应超时");
            }
            
        } catch (Exception e) {
            System.err.println("等待响应时出错: " + e.getMessage());
        }
    }
}